package cn.gong.movie.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.gong.movie.bean.Drama;
import cn.gong.movie.data.DataDrama;
import cn.gong.movie.enums.DbTaskType;
import cn.gong.movie.utils.DateUtils1;
import framework.annotation.ClickMethod;
import framework.annotation.InjectView;
import framework.base.BaseAct;
import framework.base.BaseAdap;
import framework.config.RequestCode;
import framework.config.Strings;
import framework.manage.ManageAct;

public class ActWantDramaInfo extends BaseAct {
	@InjectView(R.id.title_bar_ib_left)
	private ImageButton deleteIb;
	@InjectView(R.id.title_bar_tv_title)
	private TextView titleTv;
	@InjectView(R.id.drama_info_tv_name)
	private TextView dramaNameTv;
	@InjectView(R.id.drama_info_tv_date)
	private TextView dateTv;
	@InjectView(R.id.drama_info_lv)
	private ListView episodeLv;

	private Drama drama;
	private AdapEpisode adap;

	@Override
	public void onCreateAct(Bundle savedInstanceState) {
		super.onCreateAct(savedInstanceState);
		setContentView(R.layout.drama_info);

		drama = (Drama) getIntent().getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);

		// init title
		setText(titleTv, "剧集详情");
		deleteIb.setBackgroundResource(R.drawable.bt_title_gabbage_unpress);

		// dramaname
		setText(dramaNameTv, drama.getName());

		// initLv
		initLv();

		// setDate
		setText(dateTv, DateUtils1.format("yyyyMMdd", "yyyy-MM-dd", drama.getDate()));

	}

	private void initLv() {
		adap = new AdapEpisode();
		episodeLv.setAdapter(adap);
	}

	@ClickMethod(R.id.title_bar_ib_right)
	protected void clickClose(View view) {
		Intent data = new Intent();
		data.putExtra(Strings.INTENT_EXTRA_DRAMA, drama);
		closeActForResultOk(data);
		animTranslateLeftIn();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			clickClose(null);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	class AdapEpisode extends BaseAdap {

		@Override
		public Context getContext() {
			return getApplicationContext();
		}

		@Override
		public int getCount() {

			int num = drama.getTotalNum();
			int count = num / 4;
			count = (num % 4 == 0) ? count : (count + 1);

			return count;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflate(R.layout.episode_item);
			}

			LinearLayout ll = findLinearLayoutById(R.id.episode_item_ll, convertView);

			for (int i = 0; i < 4; i++) {
				final TextView tv = (TextView) ll.getChildAt(i);
				int num = position * 4 + i;

				if (num >= drama.getTotalNum()) {
					viewGone(tv);
				} else {
					int episode = num + 1;
					setText(tv, episode);
					viewShow(tv);

					tv.setTag(num);
					tv.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							int num = (Integer) tv.getTag();
							boolean[] episodes = drama.getEpisodes();
							if (episodes[num]) {
								drama.setSeenNum(drama.getSeenNum() - 1);
								episodes[num] = false;
								tv.setTextColor(getResources().getColor(R.color.episode_unpress));
								tv.setBackgroundResource(R.drawable.icon_episode_unpress);
							} else {
								drama.setSeenNum(drama.getSeenNum() + 1);
								episodes[num] = true;
								tv.setTextColor(getResources().getColor(R.color.episode_press));
								tv.setBackgroundResource(R.drawable.icon_episode_press);
							}
							drama.setWatchTime(System.currentTimeMillis());

							if (drama.isSeen()) {
								drama.setStatus(2);
							} else if (drama.getSeenNum() != 0) {
								drama.setStatus(0);
							} else {
								drama.setStatus(1);
							}

							log(drama);

							// if (TextUtils.isEmpty(drama.getEpisodeStr())) {
							// drama.setStatus(1);
							// } else {
							// drama.setStatus(0);
							// }
							DataDrama.updateDrama(getContext(), drama, getDBCallBack());
						}
					});
				}

			}

			return convertView;
		}
	}

	@ClickMethod(R.id.title_bar_ib_left)
	protected void clickDelete(View view) {
		AlertDialog.Builder ab = getAlertDialogBuilder();
		ab.setTitle("提示");
		ab.setMessage("是否删除");
		ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				DataDrama.deleteDrama(getContext(), drama, getDBCallBack());
			}
		});
		ab.setNegativeButton("取消", null);
		ab.create().show();
	}

	@Override
	public void onDbCallBack(int dbTaskType, Object data) {
		super.onDbCallBack(dbTaskType, data);
		switch (DbTaskType.values()[dbTaskType]) {
		case dbTsUpdateDrama:
			dbTsUpdateDrama(data);
			break;
		case dbTsDeleteDrama:
			closeActForResultOk();
			break;
		}
	}

	private void dbTsUpdateDrama(Object data) {
		this.drama = (Drama) data;
	}

	@ClickMethod(R.id.drama_info_ll_edit)
	protected void clickEdit(View view) {
		Intent intent = new Intent(getContext(), ActWantDramaInfoEdit.class);
		intent.putExtra(Strings.INTENT_EXTRA_DRAMA, drama);
		openActForResult(intent, RequestCode.EDIT_DRAMA);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == resultOk()) {
			switch (RequestCode.values()[requestCode]) {
			case EDIT_DRAMA:
				editDramaBack(data);
				break;
			}
		}
	}

	private void editDramaBack(Intent data) {
		drama = (Drama) data.getSerializableExtra(Strings.INTENT_EXTRA_DRAMA);

		// dramaname
		setText(dramaNameTv, drama.getName());

		// initLv
		adap.notifyDataSetChanged();

		// setDate
		setText(dateTv, DateUtils1.format("yyyyMMdd", "yyyy-MM-dd", drama.getDate()));

	}

}
